package com.echo.week.io;

import org.junit.Test;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.util.Arrays;

/**
 * @Author echo
 * @Description NIO 案例
 * @Date 2023/10/22.
 * @Version 1.0
 */
public class TestNIO {

    // NIO实现向本地文件中写数据
    @Test
    public void test1() throws Exception {
        //1、创建输出流
        FileOutputStream fileOutputStream = new FileOutputStream("basic.txt");
        //2、从流中获取一个通道
        FileChannel channel = fileOutputStream.getChannel();
        //3、提供一个缓冲区
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        //4、往缓冲区中写数据
        String str = "Hello aaa";
        buffer.put(str.getBytes());
        //pos初始大小9 lim最大值
        //5、翻转缓冲区：
        buffer.flip();

        //pos初始大小为0 lim9
        //6、将缓冲区写到通道中，从pos-》lim
        channel.write(buffer);
        //7、关闭流
        fileOutputStream.close();
    }

    // NIO 读取文件中的内容
    @Test
    public void test2() throws Exception {
        File file = new File("basic.txt");
        // 创建文件流
        FileInputStream fileInputStream = new FileInputStream(file);
        // 获取通道
        FileChannel channel = fileInputStream.getChannel();
        // 根据文件的大小获取一个缓冲区
        ByteBuffer buffer =  ByteBuffer.allocate((int) file.length());
        // 从通道中读取数据并保存到缓冲区中
        channel.read(buffer);
        System.out.println(new String(buffer.array()));
        //关闭流
        fileInputStream.close();
    }

    // BIO 复制文件  单通道
    @Test
    public void test3() throws Exception {
        //1、创建输出流
        FileOutputStream fileOutputStream = new FileOutputStream("basic1.txt");
        FileInputStream fileInputStream = new FileInputStream("basic.txt");
        byte[] bytes = new byte[1024];
        while (true){
            int res = fileInputStream.read(bytes);
            if (res == -1){
                break;
            }
            fileOutputStream.write(bytes,0,res);
        }
        fileOutputStream.close();
        fileInputStream.close();
    }
    // NIO 复制文件
    @Test
    public void test4() throws Exception {
        //1、创建流
        FileOutputStream fileOutputStream = new FileOutputStream("basic2.txt");
        FileInputStream fileInputStream = new FileInputStream("basic.txt");
        //获取通道
        FileChannel inputChannel = fileInputStream.getChannel();
        FileChannel outputChannel =  fileOutputStream.getChannel();

        // 复制
        outputChannel.transferFrom(inputChannel, 0,inputChannel.size());

        //关闭
        fileInputStream.close();
        fileOutputStream.close();
    }
}
